using System;
using UnityEngine;
using Voodoo.Sauce.Internal;
using Voodoo.Sauce.Internal.Utils;

namespace Voodoo.Sauce.DeviceInfo
{
	public static class AndroidNativeVolumeService
	{
		private const string TAG = "AndroidNativeVolumeService";

		private static int _streamMusic;

		private static int? _maxVolume;

		private static AndroidJavaObject _audioManager;

		private static bool _audioManagerHasError;

		private static bool _maxVolumeHasError;

		private static AndroidJavaObject DeviceAudio
		{
			get
			{
				if (_audioManager != null || _audioManagerHasError)
				{
					return _audioManager;
				}
				try
				{
					AndroidJavaObject androidJavaObject = AndroidUtils.GetCurrentActivity().Call<AndroidJavaObject>("getApplicationContext", Array.Empty<object>());
					AndroidJavaClass androidJavaClass = new AndroidJavaClass("android.media.AudioManager");
					AndroidJavaClass androidJavaClass2 = new AndroidJavaClass("android.content.Context");
					_streamMusic = androidJavaClass.GetStatic<int>("STREAM_MUSIC");
					string @static = androidJavaClass2.GetStatic<string>("AUDIO_SERVICE");
					_audioManager = androidJavaObject.Call<AndroidJavaObject>("getSystemService", new object[1] { @static });
					if (_audioManager == null)
					{
						throw new Exception("Android native function 'getSystemService' returns null");
					}
				}
				catch (Exception ex)
				{
					VoodooLog.LogError(Module.COMMON, "AndroidNativeVolumeService", "Could not read Audio Manager: " + ex.Message);
					_audioManagerHasError = true;
					return null;
				}
				return _audioManager;
			}
		}

		public static int GetSystemVolume()
		{
			if (_maxVolumeHasError)
			{
				return -1;
			}
			if (DeviceAudio == null)
			{
				return -1;
			}
			if (!_maxVolume.HasValue)
			{
				_maxVolume = DeviceAudio.Call<int>("getStreamMaxVolume", new object[1] { _streamMusic });
			}
			if (!_maxVolume.HasValue)
			{
				_maxVolumeHasError = true;
				return -1;
			}
			return (int)((float)DeviceAudio.Call<int>("getStreamVolume", new object[1] { _streamMusic }) / (float)_maxVolume.Value * 100f);
		}

		public static int RetryGetSystemVolume()
		{
			if (_maxVolumeHasError)
			{
				_maxVolumeHasError = false;
				_maxVolume = null;
			}
			if (_audioManagerHasError)
			{
				_audioManagerHasError = false;
				_audioManager = null;
			}
			return GetSystemVolume();
		}
	}
}
